package com.bnlr.lrparking.wxapi;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bnlr.lrparking.app.Application;
import com.bnlr.lrparking.R;
import com.bnlr.lrparking.base.BaseActivity;
import com.bnlr.lrparking.app.AppConfig;
import com.bnlr.lrparking.constant.LrConstant;
import com.bnlr.lrparking.constant.Urls;
import com.bnlr.lrparking.event.ClosePayEvent;
import com.bnlr.lrparking.event.StallPaySucceeEvent;
import com.bnlr.lrparking.model.BaseArrayBean;
import com.bnlr.lrparking.constant.Params;
import com.bnlr.nohttp.CallServer;
import com.bnlr.nohttp.CustomHttpListener;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.yolanda.nohttp.NoHttp;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

public class WXPayEntryActivity extends BaseActivity implements IWXAPIEventHandler {


    private int i;
    private Unbinder unbinder;
    @BindView(R.id.iv_pay_result)
    ImageView ivResult;
    @BindView(R.id.tv_pay_result)
    TextView tvResult;
    @BindView(R.id.ll_pay_value)
    LinearLayout llPayValue;
    @BindView(R.id.tv_pay_value)
    TextView tvPayValue;
    private int errorType = 0;
    private boolean isSuccess = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wxpay_call_back);
        unbinder = ButterKnife.bind(this);
        Application.mWxApi.handleIntent(getIntent(), this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        Application.mWxApi.handleIntent(intent, this);

    }

    @Override
    public void onReq(BaseReq req) {
    }

    @OnClick(R.id.pay_finish)
    public void payResultClick(View view) {
        if (Params.PAY_FROM_TAG == 2 && isSuccess) {
            EventBus.getDefault().post(new ClosePayEvent());
            EventBus.getDefault().post(new StallPaySucceeEvent());
        }
        finish();
    }

    @Override
    public void onResp(BaseResp resp) {
        errorType = resp.errCode;
        LogUtils.e("resp.errCode", resp.errCode);
        LogUtils.e("resp.errStr", resp.errStr);
        switch (resp.errCode) {
            case 0:
            case -1:
                String orderId = AppConfig.getInstance().getString("wx_order_id", "");
                sendCheck(orderId);
                break;
            case -2:
                ivResult.setImageResource(R.mipmap.icon_pay_fail);
                tvResult.setTextColor(Color.parseColor("#ea5544"));
                llPayValue.setVisibility(View.GONE);
                if (Params.PAY_FROM_TAG == 2) {
                    tvResult.setText("支付失败");
                } else {
                    tvResult.setText("充值失败");
                }

                break;
            default:
                break;
        }

    }

    private void sendCheck(String orderId) {
        try {
            LogUtils.e("Params.PAY_FROM_TAG", Params.PAY_FROM_TAG);
            if (Params.PAY_FROM_TAG == 2) {
                mRequest = NoHttp.createStringRequest(Urls.SPACE_IP, LrConstant.POST);
                mRequest.add("action", "QueryOrderResult");
                mRequest.add("orderNumber", orderId);
            } else {
                mRequest = NoHttp.createStringRequest(Urls.NEW_IP, LrConstant.POST);
                mRequest.add("action", "QueryChongZhiResult");
                mRequest.add("orderNo", orderId);
            }
            mRequest.add("phonePara", Application.DEVICE_ID);
            mRequest.add("uid", AppConfig.getInstance().getString("uid", ""));
            mRequest.add("isSuccess", errorType);
            mRequest.add("type", 1);

            CallServer.getRequestInstance().add(baseContext, mRequest,
                    new CustomHttpListener<BaseArrayBean>(baseContext, true, BaseArrayBean.class) {
                        @Override
                        public void doWork(BaseArrayBean data, String code) {

                        }

                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {
                            try {
                                super.onFinally(obj, code, isSucceed);
                                LogUtils.e("code", code);
                                if (code.equals("1")) {
                                    ivResult.setImageResource(R.mipmap.pay_seccess);
                                    if (Params.PAY_FROM_TAG == 2) {
                                        tvResult.setText("支付成功");
                                        llPayValue.setVisibility(View.GONE);
                                        isSuccess = true;
                                    } else {
                                        tvResult.setText("充值成功");
                                        tvPayValue.setText(AppConfig.getInstance().getString("wx_top_up", "0"));
                                    }

                                } else {
                                    LogUtils.e("i", i);
                                    if (i < 3) {
                                        i++;
                                        String orderId = AppConfig.getInstance().getString("wx_order_id", "");
                                        LogUtils.e("sendCheck", i);
                                        sendCheck(orderId);
                                    } else {
                                        ToastUtils.showShort(obj.getString("msg"));
                                        ivResult.setImageResource(R.mipmap.icon_pay_fail);
                                        tvResult.setTextColor(Color.parseColor("#ea5544"));
                                        if (Params.PAY_FROM_TAG == 2) {
                                            tvResult.setText("支付失败");
                                        } else {
                                            tvResult.setText("充值失败");
                                        }
                                        llPayValue.setVisibility(View.GONE);
                                    }
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }, i == 2 ? true : false);
        } catch (Exception e) {
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbinder.unbind();
        Params.PAY_FROM_TAG = 1;
    }

}